<?php

namespace app\api\controller\shop;

use addons\epay\library\Service;
use app\admin\model\Article;
use app\admin\model\Articletype;
use app\admin\model\City;
use app\admin\model\Shop;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopjoin;
use app\admin\model\Shopks;
use app\admin\model\Shopmeituan;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoptuan;
use app\admin\model\Tuanorder;
use app\admin\model\Userbalance;
use app\admin\model\Usermeituancode;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\api\service\KsService;
use app\api\service\MtUtil;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;
use Yansongda\Pay\Pay;

/**
 */
class Ks extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $appKey = "";
    protected $secret = "";

    public function _initialize()
    {
        parent::_initialize();
        $this->appKey = "2c8bce9314172fc1";
        $this->secret = "bb39c01023ce0fbb519d2b68f4457ec37fbc0e6a";
    }

    public function couponBuyList()
    {

        $page = $this->request->param('page');
        $startTime = $this->request->param('startTime');
        $endTime = $this->request->param('endTime');
        $mobile = $this->request->param('mobile');
        $where = array();



        $limit = 10;
        $offset = ($page - 1) * $limit;
        $shop_id = $this->request->param('shop_id');
        $userMeituanModel = new Usermeituancode();
        $where['Usermeituancode.shop_id'] = $shop_id;
        $where['order.status'] = array("<>", 'paying');
        $shopOrderModel = new Shoporder();
        $amount = $shopOrderModel->where('status', 'not in', ['paying', 'refund'])->where('mt_code', "<>", '')->where('shop_id', $shop_id)->sum('amount');
        $refund = $shopOrderModel->where('status', 'refund')->where('shop_id', $shop_id)->where('mt_code', "<>", '')->sum('amount');


        $list = $userMeituanModel->with(['user', 'coupon'])->where("Usermeituancode.shop_id", $shop_id)->limit($limit, $offset)->order('create_time', 'desc')->select();
        foreach ($list as $key => $val) {

        }
        $ret = array();
        $ret['list'] = $list;
        $ret['total'] = $amount;
        $ret['refund'] = $refund;


        $this->success('', $ret);
    }


    public function getCouponList()
    {

        $shop_id = $this->request->param('shop_id');
        $ksModel = new Shopks();
        $list = $ksModel->where('shop_id', $shop_id)->select();
        $this->success('', $list);
    }


    public function couponSet()
    {
        $id = $this->request->param('id');
        $hour = $this->request->param('hour');
        $room = $this->request->param('room');
        $week = $this->request->param('week');
        $start = $this->request->param('start');
        $end = $this->request->param('end');
        $type = $this->request->param('type');
        if ($start == '开始时间' || $end == '结束时间') {
            $this->error("请设置时间");
        }

        if (!$type) {
            $type = "qp";
        }

        if ($hour == 0) $this->error("请设置时长");

        $week = json_decode(htmlspecialchars_decode($week), true);
        $room = json_decode(htmlspecialchars_decode($room), true);
        $shopKsModel = new Shopks();
        $ids = array();
        foreach ($room as $key => $val) {
            $ids[] = $val['id'];
        }
        $newWeek = array();
        $w = "";
        foreach ($week as $key => $val) {
            $w .= $val['name'];
            if ($key != count($week) - 1) {
                $w .= ",";
            }
            if ($val['name'] == "一") {
                $newWeek[] = 1;
            }
            if ($val['name'] == "二") {
                $newWeek[] = 2;
            }
            if ($val['name'] == "三") {
                $newWeek[] = 3;
            }
            if ($val['name'] == "四") {
                $newWeek[] = 4;
            }
            if ($val['name'] == "五") {
                $newWeek[] = 5;
            }
            if ($val['name'] == "六") {
                $newWeek[] = 6;
            }
            if ($val['name'] == "日") {
                $newWeek[] = 7;
            }
        }

        $shopKsModel->where('id', $id)->update(['hour' => $hour, 'room_id' => json_encode($ids), 'use_time' => $start . "~" . $end,
            'week' => json_encode($newWeek), 'type' => $type]);
        $this->success('成功');

    }


    public function autoAuth()
    {

        $mtUtil = new MtUtil();
        $appKey = $this->appKey;
        $data = [
            'app_key' => $appKey,
            'app_secret' => $this->secret,
            'grant_type' => "authorize_platform",
        ];

        $url = 'https://openapi.dianping.com/router/oauth/token';
        $postdata = http_build_query($data);
        $tmpInfo = $mtUtil->curl_post($url, $postdata);


        $this->success('', $tmpInfo);
    }


    public function syncCouponInfo()
    {

        $shop_id = $this->request->param('shop_id');
        $shopModel = new Shop();
        $shop = $shopModel->where('id', $shop_id)->find();

        $merchantId = $shop['ks_id'];
        $cache = $this->longRedis->get($merchantId);
        $shopKsModel = new Shopks();
        if($cache == ''){
            $this->error("快手未授权");
        }
        $cache = json_decode($cache,true);
        $access_token = $cache['access_token'];
        $expires_in = $cache['expires_in'];
        if($expires_in <strtotime("-1 minute")){
            $ksService = new KsService();
            $p = array();
            $p['ks_id'] = $merchantId;
            $access_token = $ksService->refresh($this->longRedis,$p);
        }
        $url = "https://lbs-open.kuaishou.com/goodlife/v1/item/itemlist/batch/query";


        $req = array();
        $req['cursor'] = 0;
        $req['size'] = 90;
        $req['start_time'] = 1704682034618;
        $req['end_time'] = getMillisecond();

        $result = KsService::post($url,json_encode($req),$access_token);
        $result = json_decode($result,true);

        $list =  $result['data']['item_list'];
           foreach ($list as $key=>$val){
               $sku = $val['sku'][0];
               $name = $sku['sku_name'];
               $sku_id = $sku['sku_id'];
               $actual_amount = $sku['actual_amount']/100;
               $origin_amount = $sku['origin_amount']/100;
               $db = array();
               $db['sku_name'] = $name;
               $db['sku_id'] = $sku_id;
               $db['shop_id'] = $shop_id;
               $db['price'] = $actual_amount;
               $db['market_price']= $origin_amount;
               $shopKs = $shopKsModel->where('shop_id',$shop_id)->where('sku_id',$sku_id)->find();
               if($shopKs){
                   $shopKsModel->where('id',$shopKs['id'])->update($db);
               }else{
                   $shopKsModel->insert($db);
               }

           }
           $this->success('');


    }


    public function couponInfo()
    {

        $qr_cpde = $this->request->param('code');
        $shop_id = $this->request->param('shop_id');
        $shopModel = new Shop();
        $shop = $shopModel->where('id', $shop_id)->find();
        $open_shop_uuid = $shop['open_shop_uuid'];
        $mtUtil = new MtUtil();
        $appKey = $this->appKey;
        $secret = $this->secret; //秘钥
        $timestamp = date('Y-m-d H:i:s');
        $format = 'json';
        $v = 1;
        $sign_method = 'MD5';

        $data = [
            'app_key' => $appKey,
            'timestamp' => $timestamp,
            'sign_method' => $sign_method,
            'format' => $format,
            'session' => $shop['mt_token'],
            'v' => $v,

        ];
        $arr = [
            'receipt_code' => $qr_cpde,
            'open_shop_uuid' => $open_shop_uuid,
        ];
        $url = 'https://openapi.dianping.com/router/tuangou/receipt/prepare';//查询券
        $data = array_merge($data, $arr);
        ksort($data);
        $sign = $mtUtil->call_sign($secret, $data);//获取签名
        $data['sign'] = $sign;
        $data = array_merge($data, $arr);
        $postdata = http_build_query($data);
        $tmpInfo = $mtUtil->curl_post($url, $postdata);


        $this->success('同步成功');
    }

    public function tuangou_hexiao()
    {
        //
        $qr_cpde = $_GET['qr_code'];
        $open_shop_uuid = $_GET['open_shop_uuid'];
        $mtUtil = new MtUtil();
        // $arr 为数组 里面为应用参数
        $appKey = $this->appKey;
        $secret = $this->secret; //秘钥
        $timestamp = date('Y-m-d H:i:s');
        $format = 'json';
        $v = 1;
        $sign_method = 'MD5';
        $data = [
            'app_key' => $appKey,
            'timestamp' => $timestamp,
            'sign_method' => $sign_method,
            'format' => $format,
            'v' => $v,
        ];
        //根据不同的操作类型配置不同的参数
        //具体参数含义见 https://open.dianping.com/document/v2?docId=6000176&rootDocId=5000
        if ($_GET['type'] == 'save') {
            $arr = [
                'requestid' => '123',
                'count' => 1,
                'receipt_code' => $qr_cpde,
                'open_shop_uuid' => $open_shop_uuid,
                'app_shop_account' => '账号',
                'app_shop_accountname' => '账号名称',
            ];
            $url = 'https://openapi.dianping.com/router/tuangou/receipt/consume';//验券(核销)
        } elseif ($_GET['type'] == 'cancel') {
            $arr = [
                'app_deal_id' => $_GET['deal_id'],
                'receipt_code' => $qr_cpde,
                'open_shop_uuid' => $open_shop_uuid,
                'app_shop_account' => '账号',
                'app_shop_accountname' => '账号名称',
            ];
            $url = 'https://openapi.dianping.com/router/tuangou/receipt/reverseconsume';//撤销
        } else {
            $arr = [
                'receipt_code' => $qr_cpde,
                'open_shop_uuid' => $open_shop_uuid,
            ];
            $url = 'https://openapi.dianping.com/router/tuangou/receipt/prepare';//查询券
        }

        $data = array_merge($data, $arr);
        ksort($data);
        $sign = $mtUtil->call_sign($secret, $data);//获取签名
        $data['sign'] = $sign;
        $data = array_merge($data, $arr);
        $postdata = http_build_query($data);
        $tmpInfo = $mtUtil->curl_post($url, $postdata);

        return $tmpInfo;
    }

    /* @FunctionDesc:商家授权
     * @Params:  auth_code 用户同意授权后，回调得到的值，根据该值可获取session(也就是auth_token)
     * */
    public function auth()
    {
        $auth_code = $_GET["auth_code"];
        $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/mt/auth";

        //判断是否为回调
        if (empty($auth_code)) {
            $app_key = $this->appKey;
            $state = 'teststate';
            //回调的url,我配置为当前方法。
            $redirect_url = $url;
            $url = 'https://e.dianping.com/dz-open/merchant/auth?';
            $data = [
                'app_key' => $app_key,
                'state' => $state,
                'redirect_url' => $redirect_url
            ];
            $postdata = http_build_query($data);
            header("Location: $url$postdata");
        } else {
            //根据auth_code 获取session的授权码
            $tmpInfo = $this->shopSession($auth_code);
            error_log("======tmpInfo==" . json_encode($tmpInfo));

            //根据$session $bid 获取店铺id
            $shopInfo = $this->getShopId($tmpInfo['access_token'], $tmpInfo['bid']);
            $data = $shopInfo['data'];
            $shopModel = new Shop();
            $expires_in = $tmpInfo['expires_in'];
            $min = $expires_in / 60;
            error_log($min . "==========" . $expires_in);
            $updateTime = strtotime("+" . $min . " minutes", time());
            foreach ($data as $key => $val) {
                $open_shop_uuid = $val['open_shop_uuid'];
                $name = $val['shopname'];
                $branchname = $val['branchname'];
                $shop = $shopModel->where('mt_name', $name . "(" . $branchname . ")")->find();
                if ($shop) {
                    $shopModel->where('id', $shop['id'])->update(['open_shop_uuid' => $open_shop_uuid, 'mt_token' => $tmpInfo['access_token'], 'mt_update_time' => $updateTime]);
                }
            }
            error_log("======shopInfo====" . json_encode($shopInfo));
        }
    }


    //授权获取session
    public function shopSession($auth_code)
    {
        $mtUtil = new MtUtil();

        $app_key = $this->appKey;
        $app_secret = $this->secret;
        $grant_type = 'authorization_code';
        $redirect_url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/mt/auth";

        $data = [
            'app_key' => $app_key,
            'app_secret' => $app_secret,
            'redirect_url' => $redirect_url,
            'auth_code' => $auth_code,
            'grant_type' => $grant_type
        ];
        $postdata = http_build_query($data);
        $url = 'https://openapi.dianping.com/router/oauth/token';
        $tmpInfo = $mtUtil->curl_post($url, $postdata);
        return $tmpInfo;
    }


    //获取所有店铺的id
    public function getShopId($session, $bid)
    {
        $mtUtil = new MtUtil();
        $app_key = $this->appKey;
        $secret = $this->secret; //秘钥
        $sign_method = 'MD5';
        $timestamp = date('Y-m-d H:i:s');
        $format = 'json';
        $v = 1;
        $offset = 0;
        $limit = 20;
        $url = 'https://openapi.dianping.com/router/oauth/session/scope?';
        $data = [
            'app_key' => $app_key,
            'sign_method' => $sign_method,
            'timestamp' => $timestamp,
            'format' => $format,
            'v' => $v,
            'session' => $session,
            'bid' => $bid,
            'offset' => $offset,
            'limit' => $limit,
        ];
        error_log("===session==" . json_encode($session));
        ksort($data);
        $sign = $mtUtil->call_sign($secret, $data);
        $data['sign'] = $sign;
        $postdata = http_build_query($data);
        $tmpInfo = $mtUtil->curl_get($url . $postdata);
        return $tmpInfo;
    }


}
